//
//  WelcomViewController.swift
//  Webo10
//
//  Created by ChengXiwu on 2017/7/30.
//  Copyright © 2017年 ChengXiwu. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

class WelcomViewController: UIViewController {

    // 设置视图层次结构
    override func loadView() {
        view = backImageView
        setupUI()
    }
    
    // 视图加载完成之后后续处理,通常用来设置数据
    override func viewDidLoad() {
        super.viewDidLoad()

        // 异步加载用户头像
        iconView.sd_setImage(with: UserAccountViewModel.userAccount.avatarUrl, placeholderImage: UIImage(named: "avatar_default_big"))
    }

    // 视图已经显示,通常可以做动画/键盘处理
    override func viewDidAppear(_ animated: Bool) {
        // 更改约束,改变位置
        // 原则:所有使用约束位置的控件,不要再设置frame,自动布局系统会根据设置的约束自动计算控件的frame,如果
        // 程序员手工修改frame,会引起自动布局系统计算错误
        iconView.snp.updateConstraints { (make) in
            make.bottom.equalTo(view.snp.bottom).offset(-view.bounds.height + 200)
        }
        
        // 设置动画
        welcomeLabel.alpha = 0
        UIView.animate(withDuration: 1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: [], animations: { 
            self.view.layoutIfNeeded()
        }) { (_) in
            UIView.animate(withDuration: 0.8, animations: { 
                self.welcomeLabel.alpha = 1
            }){(_) in
                    NotificationCenter.default.post(name: WBSwitchRootViewControllerNotification, object: nil)
            }
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var backImageView: UIImageView = UIImageView(imageName: "ad_background")
    private lazy var iconView: UIImageView = {
        
        let iv = UIImageView(imageName: "avatar_default_big")
        iv.layer.cornerRadius = 45
        iv.layer.masksToBounds = true
        
        return iv
    }()
    // 欢迎标签
    private lazy var welcomeLabel: UILabel = UILabel(title: "欢迎归来", fontSize: 18)
    
    // MARK: - 设置界面
    private func setupUI(){
        // 添加控件
        view.addSubview(iconView)
        view.addSubview(welcomeLabel)
        
        // 自动布局
        iconView.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            // multipliedBy是只读属性,做动画时不允许修改
            // make.bottom.equalTo(view.snp.bottom).multipliedBy(0.7)
            make.bottom.equalTo(view.snp.bottom).offset(-200)
            make.width.equalTo(90)
            make.height.equalTo(90)
        }
        welcomeLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(iconView.snp.centerX)
            make.top.equalTo(iconView.snp.bottom).offset(16)
        }
    }
}
